import sys
from PyQt4 import QtGui, QtCore
import struct
import zlib

if sys.argv[1] == None:
	sys.exit(1)
	

filename = sys.argv[1]
f = open(filename,'rb')
content = f.read()
f.close()
if content.__len__() == 0:
	sys.exit(1)

t = struct.unpack('6i',content[0:24])
if t[0] != 8:
	sys.exit(2)
if t[1] != content.__len__():
	sys.exit(3)
x = t[3]
y = t[4]
colornum = t[5]
color = t[2]

colors = struct.unpack('%dB'%(4*colornum),zlib.decompress(content[24:(color+24)]))
c = []
n = 0
while n < colors.__len__():
	c.append(colors[n:n+4])
	n = n + 4

pointnum = x * y
points = struct.unpack("%di"%pointnum,zlib.decompress(content[(color+24):content.__len__()]))


#root = Tkinter.Tk()
#canvas = Tkinter.Canvas(root,width=x,height=y)
#n = 0
#print(points[300:320])
#for i in points:
#	x_t = n % x
#	y_t = int(n / x)
#	tk_color = "#%02x%02x%02x" % (colors[i * 4],colors[i * 4 + 1],colors[i * 4 + 2])
#	canvas.create_line(x_t,y_t,x_t,y_t,fill=tk_color)
#	n = n + 1
#Tkinter.mainloop()

class Painter(QtGui.QWidget):
	def __init__(self, x,y,parent=None):
		QtGui.QWidget.__init__(self, parent)
		self.resize(x, y)
		self.x = x
		self.y = y
		self.setWindowTitle('Image Viewer')
		self.points = None
		self.colors = []

	def set(self,colors,points):
		self.points = points
		size = colors.__len__()
		for i in xrange(0,size/4):
			self.colors.append(QtGui.QColor(colors[4 * i], colors[4 * i + 1], colors[4 * i + 2]))

	def paintEvent(self, event):
		paint = QtGui.QPainter()
		paint.begin(self)
		n = 0
		for i in self.points:
			x = n % self.x
			y = int(n / self.x)
			paint.setPen(self.colors[i])
			paint.drawPoint(x, y)
			n = n + 1
		paint.end()
	
app = QtGui.QApplication(sys.argv)
pt = Painter(x,y)
pt.set(colors,points)
pt.show()
app.exec_()